<template>
    <div>
        <!-- 搜索栏 -->
        <div style="margin: 10px 0;">
            <el-input placeholder="请输入名字" style="width: 200px;margin-right: 5px;"
                      suffix-icon="el-icon-search" v-model="role.name"></el-input>
            <el-button type="primary" @click="getAll">搜索</el-button>
            <el-button type="primary" @click="clearQuery">清空</el-button>
        </div>
        <!--操作栏-->
        <div style="margin: 10px 0;">
            <el-button type="primary" @click="handleCreate">新增<i class="el-icon-circle-plus-outline"></i>
            </el-button>
            <el-button type="danger" @click="delBatch" style="margin-right: 10px">批量删除<i
                    class="el-icon-remove-outline"></i></el-button>
        </div>
        <!--表格-->
        <el-table :data="tableData" :border="true" height="400" stripe
                  :header-cell-style="{background:'#eee'}"
                  ref="multipleTable"
                  @selection-change="handleSelectionChange">
            <el-table-column
                    type="selection"
                    width="55">
            </el-table-column>
            <el-table-column prop="id" label="ID" width="70" fixed="left">
            </el-table-column>
            <el-table-column prop="name" label="名字" width="120">
            </el-table-column>
            <el-table-column prop="tag" label="唯一标识" width="120">
            </el-table-column>
            <el-table-column prop="description" label="描述">
            </el-table-column>
            <el-table-column label="操作" width="300">
                <template slot-scope="scope">
                    <el-button
                            size="mini"
                            type="info"
                            @click="findMenu(scope.row)">分配菜单 <i class="el-icon-menu"></i>
                    </el-button>
                    <el-button
                            size="mini"
                            type="success"
                            @click="handleEdit(scope.row)">编辑 <i class="el-icon-edit"></i>
                    </el-button>
                    <el-button
                            size="mini"
                            type="danger"
                            @click="handleDelete(scope.row)">删除 <i
                            class="el-icon-remove-outline"></i></el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页控件 -->
        <div class="block">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="pageNum"
                    :page-sizes="[2, 5, 10, 20]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </div>
        <!--新增框-->
        <div>
            <el-dialog title="新增角色" :visible.sync="dialogFormVisible">
                <el-form :model="formData">
                    <el-form-item label="名字" :label-width="formLabelWidth">
                        <el-input v-model="formData.name" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="描述" :label-width="formLabelWidth">
                        <el-input v-model="formData.description" autocomplete="off"></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取 消</el-button>
                    <el-button type="primary" @click="handleAdd">确 定</el-button>
                </div>
            </el-dialog>
        </div>
        <!--编辑框-->
        <div>
            <el-dialog title="编辑角色" :visible.sync="dialogFormVisibleEdit">
                <el-form :model="formData">
                    <el-form-item label="ID" :label-width="formLabelWidth">
                        <el-input v-model="formData.id" autocomplete="off" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="名字" :label-width="formLabelWidth">
                        <el-input v-model="formData.name" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="唯一标识" :label-width="formLabelWidth">
                        <el-input v-model="formData.tag" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="描述" :label-width="formLabelWidth">
                        <el-input v-model="formData.description" autocomplete="off"></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormVisibleEdit = false">取 消</el-button>
                    <el-button type="primary" @click="handleAdd">确 定</el-button>
                </div>
            </el-dialog>
        </div>
        <!--树形菜单-->
        <div>
            <el-dialog title="分配菜单" :visible.sync="dialogMenuVisible" width="40%">
                <el-tree
                        :data="menuData"
                        show-checkbox
                        node-key="id"
                        :default-expanded-keys="expends"
                        :default-checked-keys="checks"
                        :props="defaultProps"
                        ref="tree">
                    <span class="custom-tree-node" slot-scope="{ node, data }">
                        <span><i :class="data.icon" /> {{ data.name }}</span>
                    </span>
                </el-tree>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogMenuVisible = false">取 消</el-button>
                    <el-button type="primary" @click="saveRoleMenu">确 定</el-button>
                </div>
            </el-dialog>

        </div>
    </div>
</template>

<script>
    import request from "../Api/request";

    export default {
        name: "RoleView",
        data() {
            return {
                //分页数据
                tableData: [],
                total: 0,
                pageNum: 1,
                pageSize: 2,
                role: {
                    name: '',
                },
                formData: {},
                dialogFormVisible: false,
                dialogFormVisibleEdit: false,
                dialogMenuVisible: false,
                formLabelWidth: '80px',
                multipleSelection: [],
                fileList: [],
                //树形
                menuData: [{
                    id: 1,
                    label: '主页',
                }, {
                    id: 2,
                    label: '系统管理',
                    children: [{
                        id: 3,
                        label: '用户管理'
                    }, {
                        id: 4,
                        label: '角色管理'
                    }, {
                        id: 5,
                        label: '菜单管理'
                    }, {
                        id: 6,
                        label: '文件管理'
                    },]
                }],
                defaultProps: {
                    label: 'name',
                    children: 'children'
                },
                expends:[],
                checks:[],
                roleId:0,
                roleTag:'',
            }
        },
        created() {
            this.getAll();
        },
        methods: {
            //分页
            getAll() {
                this.request.get("/roles/page", {
                    params: {
                        pageNum: this.pageNum,
                        pageSize: this.pageSize,
                        name: this.role.name,
                    }
                }).then((res) => {
                    this.tableData = res.data.records;
                    this.total = res.data.total;
                }).catch(res => {
                });
            },
            //清楚查询消息
            clearQuery() {
                this.role.name = "",
                    this.getAll()
            },
            //弹出添加窗口
            handleCreate() {
                this.dialogFormVisible = true;
                this.resetForm();
            },
            //重置表单
            resetForm() {
                this.formData = {};
            },
            //新增或修改
            handleAdd() {
                this.request.post("/roles", this.formData).then(res => {
                    if (res.flag) {
                        this.getAll();
                        this.dialogFormVisibleEdit = false;
                        this.dialogFormVisible = false;
                        this.$message.success("保存成功");
                    }
                }).catch(() => {
                    this.$message.error("保存失败");
                })
            },
            //删除
            handleDelete(row) {
                this.$confirm("此操作永久删除当前信息，是否继续？", "提示", {type: "info"}).then(() => {//确认删除
                    this.request.delete("/roles/" + row.id).then(res => {
                        if (res.flag) {
                            this.$message.success("删除成功");
                        } else {
                            this.$message.error("数据同步失败，自动刷新");
                        }
                    }).finally(() => {
                        this.getAll();
                    });
                }).catch(() => {//取消删除
                    this.$message.info("取消操作");
                });
            },
            //先查询，再编辑
            handleEdit(row) {
                this.request.get("/roles/" + row.id).then(res => {
                    //if (res.data.flag && res.data.data != null)
                    if (res.flag) {
                        this.dialogFormVisibleEdit = true;
                        this.formData = row;
                    } else {
                        this.$message.error("数据同步失败，自动刷新");
                    }
                }).finally(() => {
                    this.getAll();
                })
            },
            handleSelectionChange(val) {
                this.multipleSelection = val;//对象数组
            },
            //删除选中
            delBatch() {
                let ids = this.multipleSelection.map(value => value.id);//转化为id数组
                this.$confirm("此操作永久删除当前信息，是否继续？", "提示", {type: "info"}).then(() => {
                    this.request.post("/roles/del/batch", ids).then(res => {
                        if (res.flag) {
                            this.$message.success("删除成功");
                        } else {
                            this.$message.error("数据同步失败，自动刷新");
                        }
                    }).finally(() => {
                        this.getAll();
                    })
                }).catch(() => {
                    this.$message.info("取消操作");
                })
            },
            handleSizeChange(val) {
                this.pageSize = val;
                this.getAll();
            },
            handleCurrentChange(val) {
                this.pageNum = val;
                this.getAll();
            },


            saveRoleMenu(){
                this.request.post("/roles/roleMenu/" + this.roleId, this.$refs.tree.getCheckedKeys()).then(res=>{
                    if (res.flag) {
                        this.$message.success("绑定成功");
                        this.dialogMenuVisible = false;

                        if (this.roleTag==='ROLE_ADMIN'){
                            this.$store.commit("logout");
                        }
                    } else {
                        this.$message.error(res.msg);
                    }
                });
            },
            //请求菜单
            findMenu(role) {
                this.roleId=role.id;
                this.roleTag=role.tag;

                this.request.get("/menus", {
                    params: {
                        name: "",
                    }
                }).then((res) => {
                    this.menuData = res.data;
                    //后台返回菜单数据处理成id数组
                    this.expends=this.menuData.map(value => value.id);
                });

                this.request.get("/roles/roleMenu/" + this.roleId).then(res => {
                    this.checks = res.data;
                    //this.dialogMenuVisible = true;

                    //查询所有菜单id和选择比较，多的设置未选中
                    this.request.get("/menus/ids").then(res=>{
                        let ids = res.data;
                        ids.forEach(id=>{
                            if (!this.checks.includes(id)){
                                //bug undefined (reading 'setChecked') tree没加载
                                //解决 1、弹窗先显示加载tree 2、this.$nextTick
                                this.$nextTick(()=>{
                                    this.$refs.tree.setChecked(id, false);
                                })
                            }
                        });
                        this.dialogMenuVisible = true;

                    });
                });
            },
        }
    }
</script>

<style scoped>

</style>